package com.keyware.kd.controller.auditlog;

import com.keyware.kd.controller.BaseController;
import com.keyware.kd.repository.entity.auditlog.AuditLog;
import com.keyware.kd.repository.entity.auditlog.AuditLogSnapshot;
import com.keyware.kd.repository.entity.auditlog.UserAuditLog;
import com.keyware.kd.service.itf.auditlog.AuditLogService;
import com.keyware.kd.service.itf.auditlog.UserAuditLogService;
import com.keyware.kd.task.util.AjaxMessage;
import com.keyware.kd.utils.Constant;
import com.keyware.utils.*;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 用户日志管理模块
 */
@Controller
@RequestMapping("/userAuditLog")
public class UserAuditLogController extends BaseController{
	public static Logger logger = Logger.getLogger(UserAuditLogController.class);
	@Resource
	private UserAuditLogService userAuditLogService;
	/**
	 *@author 申鹏飞
	 *@title 跳转日志管理页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = {"/auditLog" })
	public String auditLogPage(){

		//查询出日志中所有人员
		List<UserAuditLog> userAuditLog = userAuditLogService.selectLogUserName();
		request.setAttribute("userAuditLog",userAuditLog);
		return "userAuditlog/auditLogList";
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转管理员审计页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = {"/adminAuditLog" })
	public String adminAuditLogPage(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String endDate = sdf.format(new Date());
		Calendar cl = Calendar.getInstance();
		cl.add(Calendar.MONTH, -1);	
		String startDate = sdf.format(cl.getTime());
		request.setAttribute("endDate", endDate);
		request.setAttribute("startDate", startDate);
		return "auditlog/adminAuditLog";	
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转安全审计员审计页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = {"/safeAuditLog" })
	public String safeAuditLogPage(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String endDate = sdf.format(new Date());
		Calendar cl = Calendar.getInstance();
		cl.add(Calendar.MONTH, -1);	
		String startDate = sdf.format(cl.getTime());
		request.setAttribute("endDate", endDate);
		request.setAttribute("startDate", startDate);
		return "auditlog/safeAuditLog";	
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转安全保密员审计页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = {"/safeSecretAuditLog" })
	public String safeSecretAuditLogPage(){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String endDate = sdf.format(new Date());
		Calendar cl = Calendar.getInstance();
		cl.add(Calendar.MONTH, -1);	
		String startDate = sdf.format(cl.getTime());
		request.setAttribute("endDate", endDate);
		request.setAttribute("startDate", startDate);
		return "auditlog/safeSecretAuditLog";	
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转日志管理添加页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = {"/addPage" })
	public String addPage(){
		return "auditlog/addPage";	
	}
	/**
	 *@author 申鹏飞
	 *@title 添加日志管理信息
	 *@param auditLog
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/add",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public AjaxMessage add(@ModelAttribute UserAuditLog auditLog){
		AjaxMessage ajaxMessage = new AjaxMessage();
		try {
			auditLog.setId(IdGenerator.uuid32());
			userAuditLogService.insert(auditLog);
			ajaxMessage.setCode("1");
			ajaxMessage.setMessage("保存成功");
		} catch (Exception e) {
			ajaxMessage.setCode("0");
			ajaxMessage.setMessage("系统错误,请联系管理员");
			logger.error(e);
		}
		return ajaxMessage;
	}
	/**
	 *@author 申鹏飞
	 *@title 跳转日志管理修改页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = {"/editPage" })
	public String editPage(){
		String id=request.getParameter("id");
		request.setAttribute("id", id);
		return "auditlog/editPage";	
	}
	/**
	 *@author 申鹏飞
	 *@title 获取日志管理信息
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = {"/viewInfo" })
	@ResponseBody
	public String viewInfo(){
		String id=request.getParameter("id");
		UserAuditLog auditLog = userAuditLogService.selectByPrimaryKey(id);
		return JsonUtils.objectToJsonString(auditLog);	
	}
	/**
	 *@author 申鹏飞
	 *@title 修改日志管理信息
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/edit",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public AjaxMessage edit(@ModelAttribute UserAuditLog auditLog){
		AjaxMessage ajaxMessage = new AjaxMessage();
		try {
			userAuditLogService.updateByPrimaryKey(auditLog);
			ajaxMessage.setCode("1");
			ajaxMessage.setMessage("保存成功");
		} catch (Exception e) {
			logger.error(e);
			ajaxMessage.setCode("0");
			ajaxMessage.setMessage("系统错误,请联系管理员");
		}
		return ajaxMessage;
	}
	/**
	 *@author 申鹏飞
	 *@title 查询日志管理页面
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/select",produces = "application/json; charset=utf-8")
	@ResponseBody
	public PaginationUtil selectAll(@ModelAttribute UserAuditLog auditLog){


		PaginationUtil paginationUtil = new PaginationUtil();
		try {
			paginationUtil.before(request);
			auditLog.setProjectSource(Constant.projectName);
			List<UserAuditLog> userAuditLog = userAuditLogService.selectUserAuditLogBySelective(auditLog);
			paginationUtil.after(userAuditLog);
		}catch (Exception e){
			System.out.println(e);
		}
		return paginationUtil;
	}

	/**
	 *@author 申鹏飞
	 *@title 删除日志管理信息
	 * @return
	 *@date 2016-06-17
	 */
	@RequestMapping(value = "/delete",method = RequestMethod.POST,produces = "application/json; charset=utf-8")
	@ResponseBody
	public String delete(){
		List<String> listId=IdComposeListUtil.listId(request);
		UserAuditLog auditLog = userAuditLogService.selectByPrimaryKey(listId.get(0));
		userAuditLogService.deleteAudit(listId);
		if (auditLog != null) {
			userAuditLogService.insertLog("删除日志", "日志管理", getUser_idFormSession("userName")+"删除了"+listId.size()+"条日志", request);
		}
		return "删除成功";
	}
	/**
	 *@author 赵亚舟
	 * @param projectSource
	 * @param auditLog
	 *@title 根据查询条件导出全部日志
	 *@return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/exportExcel",method = RequestMethod.GET,produces = "application/json; charset=utf-8")
	public void exportExcel(HttpServletResponse response, String projectSource,@ModelAttribute UserAuditLog auditLog) throws Exception{
        String filename = "用户操作日志.xls";
        String filePath = request.getSession().getServletContext().getRealPath("upload") +"\\"+ filename;
        //List<UserAuditLog> list = new ArrayList<UserAuditLog>();
		//List<String> logIdsList = Arrays.asList(auditLogIds);

		List<UserAuditLog> selectLogList = userAuditLogService.selectUserAuditLogBySelective(auditLog);
		//List<UserAuditLog> selectLogList = userAuditLogService.selectAudit(logIdsList);
		List<Map> logList = new ArrayList<Map>();
		for(UserAuditLog log : selectLogList){
			Map<String,String> logMap = new HashMap<String,String>();
			logMap.put("logName", log.getLogName());
			logMap.put("logNameType", log.getLogNameType());
			logMap.put("userId", log.getUserId());
			logMap.put("userName", log.getUserName());
			logMap.put("deptName", log.getDeptName());
			logMap.put("IP", log.getIpAddress());
			logMap.put("operTime", log.getOperTime());
			logMap.put("comments", log.getComments());
			logMap.put("projectSource",log.getProjectSource());
			logList.add(logMap);
		}
		exportExcel(response,logList,filePath);
	}
	public boolean exportExcel(HttpServletResponse response,List list,String filePath) {
		try {
			OutputStream os = response.getOutputStream();// 取得输出流   
			response.reset();// 清空输出流   
			response.setHeader("Content-disposition", "attachment; filename=abc.xls");// 设定输出文件头  
		
			response.setHeader("Content-Disposition", "attachment; filename=\"" + new String("用户操作日志".getBytes("gb2312"), "ISO8859-1" )+".xls"+"\"");
			response.setContentType("application/msexcel");// 定义输出类型 
			WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件   
			String tmptitle = "用户操作日志"; // 标题
			WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称  
			// 设置excel标题   
			WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16,WritableFont.BOLD,false,UnderlineStyle.NO_UNDERLINE,Colour.BLACK);   
			WritableCellFormat wc = new WritableCellFormat(wfont); 
        	// 设置居中 
       	 	wc.setAlignment(jxl.format.Alignment.CENTRE); 
       		// 设置边框线 
        	wc.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN); 
        	WritableCellFormat wc1 = new WritableCellFormat(); 
        	// 设置居中 
       	 	wc1.setAlignment(jxl.format.Alignment.CENTRE); 
       		// 设置边框线 
        	wc1.setBorder(jxl.format.Border.ALL, jxl.format.BorderLineStyle.THIN); 
        	wc1.setWrap(true);   
       		wsheet.getSettings().setDefaultColumnWidth(20);  
       		//Label  label = new Label(1, 5, "字体", wc); 
			// 开始生成主体内容                   
			wsheet.addCell(new Label(0, 0, "日志名称",wc));  
			wsheet.addCell(new Label(1, 0, "日志名称类型",wc));  
			wsheet.addCell(new Label(2, 0, "用户帐号",wc)); 
			wsheet.addCell(new Label(3, 0, "用户名",wc));  
			wsheet.addCell(new Label(4, 0, "IP",wc));
			wsheet.addCell(new Label(5, 0, "操作时间",wc));
			wsheet.addCell(new Label(6, 0, "详情",wc));

			for(int i=0;i<list.size();i++){
				HashMap projectMap = (HashMap)list.get(i);
				wsheet.addCell(new Label(0, i+1, projectMap.get("logName") == null ? "" : projectMap.get("logName").toString(),wc1));
				wsheet.addCell(new Label(1, i+1, projectMap.get("logNameType") == null ? "" : projectMap.get("logNameType").toString(),wc1));
				wsheet.addCell(new Label(2, i+1, projectMap.get("userId") == null ? "" : projectMap.get("userId").toString(),wc1));
				wsheet.addCell(new Label(3, i+1, projectMap.get("userName") == null ? "" : projectMap.get("userName").toString(),wc1));
				wsheet.addCell(new Label(4, i+1, projectMap.get("IP") == null ? "" : projectMap.get("IP").toString(),wc1));
			    wsheet.addCell(new Label(5, i+1, projectMap.get("operTime") == null ? "" : projectMap.get("operTime").toString(),wc1));
			    wsheet.addCell(new Label(6, i+1, projectMap.get("comments") == null ? "" : projectMap.get("comments").toString(),wc1));
//			    wsheet.addCell(new Label(7, i+1, projectMap.get("projectSource") == null ? "" : projectMap.get("projectSource").toString(),wc1));
			}           
			// 主体内容生成结束           
			wbook.write(); // 写入文件   
			wbook.close();
			os.close(); // 关闭流
/*			String projectExcel = PluSoft.Utils.File.read(filePath);
			response.getWriter().write(projectExcel);	
			java.io.File file = new java.io.File(filePath);
			file.delete();*/
			return true; 
		} catch(Exception ex) { 
			logger.error(ex);
			ex.printStackTrace(); 
			return false; 
		} 
    }  
	
	
}
